import { Card, Form, Input, Select, Button, message, Modal, Row, Col, Upload, Descriptions, Tag, Space } from '@/utils/antd-imports';
import { ArrowLeftOutlined, ArrowRightOutlined, SaveOutlined, PlusOutlined, UserOutlined, FileTextOutlined, RollbackOutlined, EyeOutlined } from '@/utils/icons';
import React, { useState, useEffect, useRef } from 'react';

import Steps from 'antd/es/steps';


import DatePicker from 'antd/es/date-picker';
import InputNumber from 'antd/es/input-number';











import dayjs from 'dayjs';
import fileApi from '../../api/fileApi';
import employeeApi from '../../api/employeeApi';

const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;

// 模拟数据
const mockDepartments = [
  { id: 1, name: '研发部' },
  { id: 2, name: '市场部' },
  { id: 3, name: '人事部' },
  { id: 4, name: '财务部' },
  { id: 5, name: '行政部' }
];

const mockTeams = [
  { id: 1, name: '前端组', department: '研发部' },
  { id: 2, name: '后端组', department: '研发部' },
  { id: 3, name: '测试组', department: '研发部' },
  { id: 4, name: '设计组', department: '市场部' },
  { id: 5, name: '产品组', department: '市场部' }
];

const mockPositions = [
  { id: 1, name: '工程师' },
  { id: 2, name: '经理' },
  { id: 3, name: '主管' },
  { id: 4, name: '专员' },
  { id: 5, name: '助理' }
];

const mockEmployeeTypes = [
  { value: 'FT', label: '正式员工' },
  { value: 'PT', label: '兼职员工' },
  { value: 'IN', label: '实习生' }
];

const mockContractRenewed = [
  { value: 'Y', label: '是' },
  { value: 'N', label: '否' }
];

const mockEducationLevels = [
  { value: 'high_school', label: '高中' },
  { value: 'college', label: '大专' },
  { value: 'bachelor', label: '本科' },
  { value: 'master', label: '硕士' },
  { value: 'phd', label: '博士' }
];

const mockPoliticalStatus = [
  { value: 'CP', label: '党员' },
  { value: 'YL', label: '团员' },
  { value: 'MZ', label: '群众' },
  { value: 'DP', label: '民主党派' }
];

const mockMaritalStatus = [
  { value: 'M', label: '已婚' },
  { value: 'S', label: '未婚' },
  { value: 'D', label: '离异' }
];

const mockEthnicGroups = [
  { value: 'han', label: '汉族' },
  { value: 'hui', label: '回族' },
  { value: 'manchu', label: '满族' },
  { value: 'mongol', label: '蒙古族' },
  { value: 'tibetan', label: '藏族' }
];

const mockBanks = [
  { value: 'icbc', label: '工商银行' },
  { value: 'ccb', label: '建设银行' },
  { value: 'abc', label: '农业银行' },
  { value: 'boc', label: '中国银行' },
  { value: 'cmb', label: '招商银行' }
];

const mockStatusOptions = [
  { value: 1, label: '在职' },
  { value: 0, label: '离职' },
  { value: 2, label: '休假' }
];

const safeDayjs = (date) => {
  if (!date) return null;
  if (dayjs.isDayjs(date)) return date;
  try {
    return dayjs(date);
  } catch (e) {
    console.error('日期转换错误:', e);
    return null;
  }
};

const EmployeeForm = ({ mode = 'create', employeeId, onBack }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  const [documentForm] = Form.useForm();
  const [saving, setSaving] = useState(false);
  const [employeeData, setEmployeeData] = useState({});
  const [hasChanges, setHasChanges] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [departmentSearch, setDepartmentSearch] = useState('');
  const [teamSearch, setTeamSearch] = useState('');
  const [positionSearch, setPositionSearch] = useState('');
  const [uploadingFiles, setUploadingFiles] = useState({});
  const [selectedFiles, setSelectedFiles] = useState({}); // 存储选中的文件

  const initialValues = useRef({});

  const steps = [
    { title: '基本信息', icon: <UserOutlined /> },
    { title: '文件附件', icon: <FileTextOutlined /> },
  ];

  const documentTypes = [
    { name: 'entryForm', label: '入职登记表', uploadFn: (file) => uploadDocument('entryForm', file) },
    { name: 'idCardCopy', label: '身份证复印件', uploadFn: (file) => uploadEmployeeDocument(employeeId, 'id_cards', file) },
    { name: 'diploma', label: '学历毕业证书', uploadFn: (file) => uploadEmployeeDocument(employeeId, 'education', file) },
    { name: 'degreeCertificate', label: '学位证书', uploadFn: (file) => uploadEmployeeDocument(employeeId, 'education', file) },
    { name: 'bankCardCopy', label: '银行卡复印件', uploadFn: (file) => uploadDocument('bankCardCopy', file) },
    { name: 'resume', label: '简历', uploadFn: (file) => uploadDocument('resume', file) },
    { name: 'leavingCertificate', label: '离职证明', uploadFn: (file) => uploadDocument('leavingCertificate', file) },
    { name: 'medicalReport', label: '三甲体检报告', uploadFn: (file) => uploadDocument('medicalReport', file) },
    { name: 'confidentialityAgreement', label: '保密协议', uploadFn: (file) => uploadDocument('confidentialityAgreement', file) },
    { name: 'trainingAgreement', label: '员工培训协议', uploadFn: (file) => uploadDocument('trainingAgreement', file) },
    { name: 'rulesConfirmation', label: '规章制度确认书', uploadFn: (file) => uploadDocument('rulesConfirmation', file) },
    { name: 'codeOfConduct', label: '员工行为准则', uploadFn: (file) => uploadDocument('codeOfConduct', file) }
  ];

// 选择文件（不上传）
const selectFile = (fieldName, file) => {
  console.log('[selectFile] 选择文件', { fieldName, file });
  
  // 检查文件大小限制（5MB）
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    message.error(`文件大小超过限制，最大允许5MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
    return false;
  }
  
  // 存储选中的文件
  setSelectedFiles(prev => ({
    ...prev,
    [fieldName]: file
  }));
  
  const documentLabel = documentTypes.find(d => d.name === fieldName)?.label || fieldName;
  message.success(`${documentLabel}已选择，点击完成后将上传`);
  return false; // 阻止自动上传
};

// 上传文件
const uploadDocument = async (fieldName, file) => {
  try {
    console.log('[uploadDocument] 开始上传文件', { fieldName, file });
    setUploadingFiles(prev => ({ ...prev, [fieldName]: true }));
    
    console.log('[uploadDocument] 调用fileApi.uploadFile');
    const response = await fileApi.uploadFile('documents', file);
    console.log('[uploadDocument] 上传响应:', response);
    
    // 处理响应数据
    let filePath;
    if (response && typeof response === 'object') {
      // 处理标准JSON响应 {code, message, data}
      if (response.code === 200 && response.data) {
        filePath = response.data;
      } else {
        throw new Error(response.message || '上传失败');
      }
    } else if (typeof response === 'string') {
      // 处理直接返回字符串路径的情况
      filePath = response;
    } else {
      throw new Error('无效的响应格式');
    }
    
    // 确保路径格式正确
    filePath = String(filePath).replace(/\\/g, '/');
    console.log('[uploadDocument] 处理后的文件路径:', filePath);
    
    // 更新表单和状态
    documentForm.setFieldsValue({ [fieldName]: filePath });
    setEmployeeData(prev => ({
      ...prev,
      step1: {
        ...prev.step1,
        [fieldName]: filePath
      }
    }));
    
    const documentLabel = documentTypes.find(d => d.name === fieldName)?.label || fieldName;
    message.success(`${documentLabel}上传成功`);
    return filePath;
  } catch (error) {
    console.error('[uploadDocument] 上传失败:', error);
    const documentLabel = documentTypes.find(d => d.name === fieldName)?.label || fieldName;
    message.error(`${documentLabel}上传失败: ${error.message}`);
    throw error;
  } finally {
    setUploadingFiles(prev => ({ ...prev, [fieldName]: false }));
  }
};

  const uploadEmployeeDocument = async (employeeId, subDirectory, file) => {
    if (!employeeId) {
      message.warning('请先保存员工基本信息');
      return false;
    }
    try {
      const fieldName = documentTypes.find(d => d.uploadFn.toString().includes(subDirectory))?.name;
      if (fieldName) {
        setUploadingFiles(prev => ({ ...prev, [fieldName]: true }));
      }
      const response = await fileApi.uploadFile('employee', file, `${employeeId}/${subDirectory}`);
      const filePath = response.data.replace(/\\/g, '/');
      if (fieldName) {
        documentForm.setFieldsValue({ [fieldName]: filePath });
        setEmployeeData(prev => ({
          ...prev,
          step1: {
            ...prev.step1,
            [fieldName]: filePath
          }
        }));
        message.success(`${documentTypes.find(d => d.name === fieldName).label}上传成功`);
      }
      return false;
    } catch (error) {
      console.error('上传失败:', error);
      message.error('文件上传失败');
      return false;
    } finally {
      if (fieldName) {
        setUploadingFiles(prev => ({ ...prev, [fieldName]: false }));
      }
    }
  };

  useEffect(() => {
    const loadEmployeeData = async () => {
      console.log('[loadEmployeeData] Loading employee data, mode:', mode, 'employeeId:', employeeId);
      try {
        const draftData = localStorage.getItem('employeeFormDraft');
        
        if (mode === 'edit' && employeeId) {
          console.log('[loadEmployeeData] 编辑模式，加载员工ID:', employeeId);
          const response = await employeeApi.getEmployeeDetail(employeeId);
          console.log('[loadEmployeeData] 员工详情响应:', response);
          
          const employeeDetail = response.data || response;
          console.log('[loadEmployeeData] 员工详情数据:', employeeDetail);
          
          // 处理日期字段
          const dateFields = ['birthday', 'hireDate', 'confirmationDate', 'graduationDate', 'latestContractStart', 'latestContractEnd'];
          dateFields.forEach(field => {
            if (employeeDetail[field]) {
              console.log(`[loadEmployeeData] 处理日期字段 ${field}:`, employeeDetail[field]);
              employeeDetail[field] = safeDayjs(employeeDetail[field]);
              console.log(`[loadEmployeeData] 转换后 ${field}:`, employeeDetail[field]);
            }
          });
          
          // 处理性别字段转换
          if (employeeDetail.gender === '男') {
            employeeDetail.gender = 'M';
          } else if (employeeDetail.gender === '女') {
            employeeDetail.gender = 'F';
          }
          
          // 处理婚姻状况字段转换
          if (employeeDetail.maritalStatus === '已婚') {
            employeeDetail.maritalStatus = 'M';
          } else if (employeeDetail.maritalStatus === '未婚') {
            employeeDetail.maritalStatus = 'S';
          } else if (employeeDetail.maritalStatus === '离异') {
            employeeDetail.maritalStatus = 'D';
          }
          
          // 处理员工类型字段转换
          if (employeeDetail.employeeType === '正式员工') {
            employeeDetail.employeeType = 'FT';
          } else if (employeeDetail.employeeType === '兼职员工') {
            employeeDetail.employeeType = 'PT';
          } else if (employeeDetail.employeeType === '实习生') {
            employeeDetail.employeeType = 'IN';
          }
          
          // 处理学历字段转换
          if (employeeDetail.education === '高中') {
            employeeDetail.education = 'high_school';
          } else if (employeeDetail.education === '大专') {
            employeeDetail.education = 'college';
          } else if (employeeDetail.education === '本科') {
            employeeDetail.education = 'bachelor';
          } else if (employeeDetail.education === '硕士') {
            employeeDetail.education = 'master';
          } else if (employeeDetail.education === '博士') {
            employeeDetail.education = 'phd';
          }
          
          // 处理政治面貌字段转换
          if (employeeDetail.politicalStatus === '党员') {
            employeeDetail.politicalStatus = 'CP';
          } else if (employeeDetail.politicalStatus === '团员') {
            employeeDetail.politicalStatus = 'YL';
          } else if (employeeDetail.politicalStatus === '群众') {
            employeeDetail.politicalStatus = 'MZ';
          } else if (employeeDetail.politicalStatus === '民主党派') {
            employeeDetail.politicalStatus = 'DP';
          }
          
          // 处理民族字段转换
          if (employeeDetail.ethnicity === '汉族') {
            employeeDetail.ethnicity = 'han';
          } else if (employeeDetail.ethnicity === '回族') {
            employeeDetail.ethnicity = 'hui';
          } else if (employeeDetail.ethnicity === '满族') {
            employeeDetail.ethnicity = 'manchu';
          } else if (employeeDetail.ethnicity === '蒙古族') {
            employeeDetail.ethnicity = 'mongol';
          } else if (employeeDetail.ethnicity === '藏族') {
            employeeDetail.ethnicity = 'tibetan';
          }
          
          // 处理银行字段转换
          if (employeeDetail.bankName === '工商银行') {
            employeeDetail.bankName = 'icbc';
          } else if (employeeDetail.bankName === '建设银行') {
            employeeDetail.bankName = 'ccb';
          } else if (employeeDetail.bankName === '农业银行') {
            employeeDetail.bankName = 'abc';
          } else if (employeeDetail.bankName === '中国银行') {
            employeeDetail.bankName = 'boc';
          } else if (employeeDetail.bankName === '招商银行') {
            employeeDetail.bankName = 'cmb';
          }
          
          // 处理合同续签字段转换
          if (employeeDetail.contractRenewed === '是') {
            employeeDetail.contractRenewed = 'Y';
          } else if (employeeDetail.contractRenewed === '否') {
            employeeDetail.contractRenewed = 'N';
          }
          
          // 处理试用状态字段转换
          if (employeeDetail.probation === '试用期') {
            employeeDetail.probation = 'probation';
          } else if (employeeDetail.probation === '已转正') {
            employeeDetail.probation = 'confirmed';
          }
          
          // 处理状态字段转换
          if (employeeDetail.status === '在职') {
            employeeDetail.status = 1;
          } else if (employeeDetail.status === '离职') {
            employeeDetail.status = 0;
          } else if (employeeDetail.status === '休假') {
            employeeDetail.status = 2;
          }
          
          console.log('[loadEmployeeData] 处理后的员工数据:', employeeDetail);
          
          // 加载文件信息
          let fileInfo = {};
          try {
            const fileResponse = await fileApi.listFiles('employee', employeeId);
            console.log('[loadEmployeeData] 文件列表响应:', fileResponse);
            
            if (fileResponse.success && fileResponse.data) {
              fileInfo = fileResponse.data.reduce((acc, file) => {
                const field = documentTypes.find(d => file.name.includes(d.name))?.name;
                if (field) {
                  acc[field] = file.name;
                }
                return acc;
              }, {});
            }
          } catch (fileError) {
            console.error('[loadEmployeeData] 加载文件列表失败:', fileError);
          }
          
          console.log('[loadEmployeeData] 文件信息:', fileInfo);
          
          const employeeData = {
            step0: employeeDetail,
            step1: fileInfo
          };
          
          console.log('[loadEmployeeData] 最终员工数据:', employeeData);
          
          setEmployeeData(employeeData);
          form.setFieldsValue(employeeData.step0);
          documentForm.setFieldsValue(employeeData.step1);
          
          initialValues.current = {
            step0: { ...employeeData.step0 },
            step1: { ...employeeData.step1 }
          };
          
          console.log('[loadEmployeeData] 表单字段已填充');
        } else if (draftData) {
          const parsedDraft = JSON.parse(draftData);
          const dateFields = ['birthday', 'hireDate', 'confirmationDate', 'graduationDate', 'latestContractStart', 'latestContractEnd'];
          dateFields.forEach(field => {
            if (parsedDraft.step0 && parsedDraft.step0[field]) {
              parsedDraft.step0[field] = safeDayjs(parsedDraft.step0[field]);
            }
          });
          
          setEmployeeData(parsedDraft);
          form.setFieldsValue(parsedDraft.step0);
          documentForm.setFieldsValue(parsedDraft.step1);
          
          initialValues.current = {
            step0: { ...parsedDraft.step0 },
            step1: { ...parsedDraft.step1 }
          };
        } else {
          const defaultEmployeeData = {
            step0: {
              projectCode: `PROJ${employeeId || 'NEW'}`,
              clientUnit: '',
              department: '',
              team: '',
              position: '',
              employeeType: 'FT',
              name: '',
              gender: 'M',
              maritalStatus: 'S',
              nativePlace: '',
              ethnicity: 'han',
              politicalStatus: 'MZ',
              idCard: '',
              birthday: null,
              registeredAddress: '',
              currentAddress: '',
              phone: '',
              wechat: '',
              email: '',
              hireDate: dayjs(),
              confirmationDate: null,
              education: 'bachelor',
              major: '',
              university: '',
              graduationDate: null,
              skillCertificates: '',
              baseSalary: 0,
              emergencyContact: '',
              emergencyPhone: '',
              bankAccount: '',
              bankName: 'icbc',
              contractRenewed: 'N',
              renewalCount: 0,
              latestContractStart: dayjs(),
              latestContractEnd: dayjs().add(3, 'years'),
              contractCompany: '',
              remarks: '',
              status: 'active',
              probation: 'probation'
            },
            step1: documentTypes.reduce((acc, doc) => {
              acc[doc.name] = '';
              return acc;
            }, {})
          };
          
          setEmployeeData(defaultEmployeeData);
          form.setFieldsValue(defaultEmployeeData.step0);
          documentForm.setFieldsValue(defaultEmployeeData.step1);
          
          initialValues.current = {
            step0: { ...defaultEmployeeData.step0 },
            step1: { ...defaultEmployeeData.step1 }
          };
        }
      } catch (error) {
        console.error('加载员工数据失败:', error);
        message.error('加载员工数据失败');
      }
    };
    
    loadEmployeeData();
  }, [mode, employeeId, form, documentForm]);

  const checkFormChanges = () => {
    try {
      const currentValues = {
        step0: form.getFieldsValue(),
        step1: documentForm.getFieldsValue()
      };
      
      const isChanged = Object.keys(currentValues).some(step => {
        const currentStepValues = currentValues[step];
        const initialStepValues = initialValues.current[step] || {};
        
        return Object.keys(currentStepValues).some(key => {
          return JSON.stringify(currentStepValues[key]) !== JSON.stringify(initialStepValues[key]);
        });
      });
      
      setHasChanges(isChanged);
      return isChanged;
    } catch (error) {
      console.error('检查表单变化失败:', error);
      return false;
    }
  };

  const checkUnsavedChanges = () => {
    return hasChanges && !employeeData[`step${currentStep}`];
  };

  const handleBack = async () => {
    if (checkFormChanges()) {
      Modal.confirm({
        title: '未保存的更改',
        content: '当前有未保存的更改，是否要保存后再返回？',
        okText: '保存并返回',
        cancelText: '不保存返回',
        onOk: async () => {
          try {
            await handleSave();
            onBack();
          } catch (error) {
            console.error('保存失败:', error);
          }
        },
        onCancel: () => {
          onBack();
        }
      });
    } else {
      onBack();
    }
  };

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

const handleSave = async () => {
  console.log('[handleSave] Starting save process...');
  
  try {
    console.log('[handleSave] Setting saving state to true');
    setSaving(true); // 标记保存中状态
    
    let values;
    try {
      console.log('[handleSave] Validating form fields...');
      // 1. 验证并获取表单数据
      values = await form.validateFields();
      console.log('[handleSave] Form validation successful. Values:', values);
      
      // 2. 转换日期字段
      console.log('[handleSave] Processing date fields...');
      const dateFields = ['birthday', 'hireDate', 'confirmationDate', 'graduationDate', 'latestContractStart', 'latestContractEnd'];
      dateFields.forEach(field => {
        if (values[field]) {
          console.log(`[handleSave] Converting date field ${field}:`, values[field]);
          values[field] = safeDayjs(values[field]);
          console.log(`[handleSave] Converted ${field} to:`, values[field]);
        }
      });
      
      // 3. 处理性别字段（转为单字符）
      console.log('[handleSave] Processing gender field:', values.gender);
      values.gender = values.gender === 'male' ? 'M' : 'F';
      console.log('[handleSave] Converted gender to:', values.gender);
      
      // 4. 保存到本地存储和状态
      console.log('[handleSave] Preparing draft data...');
      const draftData = {
        ...employeeData,
        step0: {
          ...values,
          savedAt: new Date().toISOString()
        }
      };
      
      console.log('[handleSave] Saving to localStorage...');
      localStorage.setItem('employeeFormDraft', JSON.stringify(draftData));
      console.log('[handleSave] localStorage updated successfully');
      
      // 5. 更新状态和初始值
      console.log('[handleSave] Updating employeeData state...');
      setEmployeeData(draftData);
      initialValues.current.step0 = { ...values };
      setHasChanges(false);
      console.log('[handleSave] State updated successfully');
      
      message.success('员工基本信息已保存');
      console.log('[handleSave] Success message shown');
    } catch (error) {
      // 6. 处理表单验证错误
      console.error('[handleSave] Form validation failed:', error);
      if (error.errorFields?.length > 0) {
        console.error('[handleSave] Validation error details:', error.errorFields);
        const firstError = error.errorFields[0];
        const errorMessage = `${firstError.name.join('.')}: ${firstError.errors.join(', ')}`;
        console.error('[handleSave] Showing error message:', errorMessage);
        message.error(errorMessage);
      } else {
        console.error('[handleSave] Generic validation error');
        message.error('表单验证失败，请检查填写内容');
      }
      return;
    }

    // 7. 如果是文件步骤，单独保存文件信息
    if (currentStep === 1) {
      console.log('[handleSave] Current step is 1 (files), processing file data...');
      const fileValues = documentForm.getFieldsValue();
      console.log('[handleSave] File values:', fileValues);
      
      setEmployeeData(prev => {
        const newData = {
          ...prev,
          step1: {
            ...fileValues,
            savedAt: new Date().toISOString()
          }
        };
        console.log('[handleSave] Updated employeeData with files:', newData);
        return newData;
      });
      
      initialValues.current.step1 = { ...fileValues };
      console.log('[handleSave] Updated initialValues with files');
      
      message.success('文件信息已更新');
      console.log('[handleSave] File update success message shown');
    }
  } catch (error) {
    console.error('[handleSave] Unexpected error during save:', error);
    console.error('[handleSave] Error details:', {
      message: error.message,
      stack: error.stack,
      currentStep,
      employeeData
    });
    message.error('保存失败，请检查表单');
  } finally {
    console.log('[handleSave] Final cleanup - setting saving to false');
    setSaving(false); // 重置保存状态
    console.log('[handleSave] Save process completed');
  }
};

const handleNext = async () => {
  try {
    console.log('开始处理下一步操作，当前步骤:', currentStep);
    
    // 在切换步骤前，保存当前步骤的数据
    const currentFormValues = form.getFieldsValue();
    console.log('当前步骤的表单值:', currentFormValues);
    
    if (Object.keys(currentFormValues).length > 0) {
      setEmployeeData(prev => ({
        ...prev,
        step0: { ...prev.step0, ...currentFormValues }
      }));
      console.log('已保存当前步骤数据到 employeeData');
    }
    
    // 直接切换到下一步，不需要保存确认
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
      console.log('已切换到步骤:', currentStep + 1);
    }
  } catch (error) {
    console.error('步骤切换过程中发生错误:', error);
    message.error('步骤切换失败，请稍后重试');
  }
};
const handleComplete = async () => {
  // 防重复提交
  if (saving) {
    console.log('[handleComplete] Already saving, skipping...');
    return;
  }
  
  console.groupCollapsed('[handleComplete] Starting employee creation process');
  console.log('[handleComplete] Mode:', mode);
  console.log('[handleComplete] Employee ID:', employeeId);
  console.log('[handleComplete] Current step:', currentStep);
  
  try {
    setSaving(true); // 立即设置为保存中
    
    // 1. 获取基本信息表单值
    console.log('[handleComplete] Getting basic info form fields...');
    console.log('[handleComplete] employeeData.step0:', employeeData.step0);
    
    // 使用 employeeData.step0 作为基本信息源
    // 因为表单值在非 step0 时无法获取到所有字段
    let formValues = employeeData.step0 || {};
    
    // 如果不在 step0，尝试合并当前表单值
    if (currentStep !== 0) {
      console.log('[handleComplete] 当前不在 step0，合并当前表单值');
      const currentFormValues = form.getFieldsValue();
      console.log('[handleComplete] 当前表单值:', currentFormValues);
      
      // 如果有有效的数据，合并它们
      if (currentFormValues && Object.keys(currentFormValues).length > 0) {
        formValues = { ...formValues, ...currentFormValues };
      }
    }
    
    console.log('[handleComplete] Final form values to use:', formValues);
    console.log('[handleComplete] Form values count:', Object.keys(formValues).length);
    console.log('[handleComplete] Form values - name:', formValues.name);
    console.log('[handleComplete] Form values - idCard:', formValues.idCard);
    console.log('[handleComplete] Form values - phone:', formValues.phone);
    console.log('[handleComplete] Form values - employeeType:', formValues.employeeType);
    
    // 2. 上传选中的文件
    console.log('[handleComplete] Uploading selected files...');
    const fileUploadPromises = [];
    const uploadedFiles = {};
    
    for (const [fieldName, file] of Object.entries(selectedFiles)) {
      if (file) {
        console.log(`[handleComplete] Uploading file for ${fieldName}:`, file.name);
        const uploadPromise = uploadDocument(fieldName, file)
          .then(filePath => {
            uploadedFiles[fieldName] = filePath;
            console.log(`[handleComplete] File uploaded successfully for ${fieldName}:`, filePath);
          })
          .catch(error => {
            console.error(`[handleComplete] File upload failed for ${fieldName}:`, error);
            throw error;
          });
        fileUploadPromises.push(uploadPromise);
      }
    }
    
    // 等待所有文件上传完成
    if (fileUploadPromises.length > 0) {
      console.log('[handleComplete] Waiting for file uploads to complete...');
      await Promise.all(fileUploadPromises);
      console.log('[handleComplete] All files uploaded successfully');
    }

    // 2. 准备提交数据 - 按照API文档格式
    console.log('[handleComplete] Preparing submission data...');
    const submitData = {
      // ========== 必填字段 ==========
      employeeType: formValues.employeeType === 'FT' ? '正式' : 
                   formValues.employeeType === 'PT' ? '兼职' : '实习',
      name: formValues.name || '',
      gender: formValues.gender === 'M' ? '男' : '女',
      maritalStatus: formValues.maritalStatus === 'M' ? '已婚' : 
                    formValues.maritalStatus === 'S' ? '未婚' : '离异',
      nativePlace: formValues.nativePlace || '',
      politicalStatus: formValues.politicalStatus === 'CP' ? '党员' :
                      formValues.politicalStatus === 'YL' ? '团员' :
                      formValues.politicalStatus === 'MZ' ? '群众' : '民主党派',
      birthday: formValues.birthday ? dayjs(formValues.birthday).format('YYYY-MM-DD') : null,
      idCard: formValues.idCard || '',
      registeredAddress: formValues.registeredAddress || '',
      phone: formValues.phone || '',
      wechat: formValues.wechat || '',
      email: formValues.email || '',
      education: formValues.education === 'high_school' ? '高中' :
                formValues.education === 'college' ? '大专' :
                formValues.education === 'bachelor' ? '本科' :
                formValues.education === 'master' ? '硕士' : '博士',
      major: formValues.major || '',
      graduationDate: formValues.graduationDate ? dayjs(formValues.graduationDate).format('YYYY-MM-DD') : null,
      emergencyContact: formValues.emergencyContact || '',
      emergencyPhone: formValues.emergencyPhone || '',
      
      // ========== 可选字段 ==========
      projectCode: formValues.projectCode || '',
      clientUnit: formValues.clientUnit || '',
      department: formValues.department || '',
      team: formValues.team || '',
      position: formValues.position || '',
      ethnicity: formValues.ethnicity === 'han' ? '汉族' :
                formValues.ethnicity === 'hui' ? '回族' :
                formValues.ethnicity === 'manchu' ? '满族' :
                formValues.ethnicity === 'mongol' ? '蒙古族' : '藏族',
      currentAddress: formValues.currentAddress || '',
      employeeCode: '', // 系统自动生成
      hireDate: formValues.hireDate ? dayjs(formValues.hireDate).format('YYYY-MM-DD') : null,
      confirmationDate: formValues.confirmationDate ? dayjs(formValues.confirmationDate).format('YYYY-MM-DD') : null,
      probation: formValues.probation === 'probation' ? '试用期' : '已转正',
      university: formValues.university || '',
      skillCertificates: formValues.skillCertificates || '',
      baseSalary: formValues.baseSalary || 0,
      hourlyRate: formValues.hourlyRate || 0,
      bankAccount: formValues.bankAccount || '',
      bankName: formValues.bankName === 'icbc' ? '工商银行' :
               formValues.bankName === 'ccb' ? '建设银行' :
               formValues.bankName === 'abc' ? '农业银行' :
               formValues.bankName === 'boc' ? '中国银行' : '招商银行',
      contractRenewed: formValues.contractRenewed === 'Y' ? '是' : '否',
      renewalCount: formValues.renewalCount || 0,
      latestContractStart: formValues.latestContractStart ? dayjs(formValues.latestContractStart).format('YYYY-MM-DD') : null,
      latestContractEnd: formValues.latestContractEnd ? dayjs(formValues.latestContractEnd).format('YYYY-MM-DD') : null,
      contractCompany: formValues.contractCompany || '',
      
      // ========== 文件信息 ==========
      entryForm: uploadedFiles.entryForm || documentForm.getFieldValue('entryForm') || '未上传',
      idCardCopy: uploadedFiles.idCardCopy || documentForm.getFieldValue('idCardCopy') || '未上传',
      diploma: uploadedFiles.diploma || documentForm.getFieldValue('diploma') || '未上传',
      degreeCertificate: uploadedFiles.degreeCertificate || documentForm.getFieldValue('degreeCertificate') || '未上传',
      bankCardCopy: uploadedFiles.bankCardCopy || documentForm.getFieldValue('bankCardCopy') || '未上传',
      resume: uploadedFiles.resume || documentForm.getFieldValue('resume') || '未上传',
      leavingCertificate: uploadedFiles.leavingCertificate || documentForm.getFieldValue('leavingCertificate') || '未上传',
      medicalReport: uploadedFiles.medicalReport || documentForm.getFieldValue('medicalReport') || '未上传',
      confidentialityAgreement: uploadedFiles.confidentialityAgreement || documentForm.getFieldValue('confidentialityAgreement') || '未上传',
      trainingAgreement: uploadedFiles.trainingAgreement || documentForm.getFieldValue('trainingAgreement') || '未上传',
      rulesConfirmation: uploadedFiles.rulesConfirmation || documentForm.getFieldValue('rulesConfirmation') || '未上传',
      codeOfConduct: uploadedFiles.codeOfConduct || documentForm.getFieldValue('codeOfConduct') || '未上传',
      
      // ========== 其他信息 ==========
      remarks: formValues.remarks || ''
    };

    // 3. 验证必填字段
    console.log('[handleComplete] Checking required fields...');
    console.log('[handleComplete] Submit data preview:', {
      name: submitData.name,
      idCard: submitData.idCard,
      phone: submitData.phone
    });
    
    const requiredFields = [
      { field: 'name', name: '姓名' },
      { field: 'idCard', name: '身份证号' },
      { field: 'phone', name: '手机号' }
    ];
    
    for (const { field, name } of requiredFields) {
      const fieldValue = submitData[field];
      console.log(`[handleComplete] 检查字段 ${field}(${name}):`, fieldValue);
      if (!fieldValue || fieldValue === '' || fieldValue === null || fieldValue === undefined) {
        const errorMsg = `请填写${name}字段`;
        console.error(`[handleComplete] 必填字段验证失败: ${field} = ${fieldValue}`);
        console.error(`[handleComplete] 验证终止，返回错误`);
        message.error(errorMsg);
        return;
      }
    }
    
    console.log('[handleComplete] Required fields validation passed');
    console.log('[handleComplete] Submit data prepared:', submitData);
    console.log('[handleComplete] Name:', submitData.name, 'ID Card:', submitData.idCard, 'Phone:', submitData.phone);
    console.log('[handleComplete] 继续执行后续流程...');

    // 4. 记录完整的提交数据
    console.groupCollapsed('[handleComplete] Full submission data');
    console.log('=== 基本信息 ===');
    console.log('姓名:', submitData.name);
    console.log('性别:', submitData.gender);
    console.log('身份证号:', submitData.idCard);
    console.log('电话:', submitData.phone);
    console.log('邮箱:', submitData.email);
    console.log('生日:', submitData.birthday);
    console.log('婚姻状况:', submitData.maritalStatus);
    
    console.log('=== 工作信息 ===');
    console.log('部门:', submitData.department);
    console.log('团队:', submitData.team);
    console.log('岗位:', submitData.position);
    console.log('入职日期:', submitData.hireDate);
    console.log('状态:', submitData.status);
    
    console.log('=== 教育信息 ===');
    console.log('学历:', submitData.education);
    console.log('专业:', submitData.major);
    console.log('毕业院校:', submitData.university);
    
    console.log('=== 薪资信息 ===');
    console.log('基本工资:', submitData.baseSalary);
    console.log('时薪:', submitData.hourlyRate);
    
    console.log('=== 银行信息 ===');
    console.log('银行账号:', submitData.bankAccount);
    console.log('开户行:', submitData.bankName);
    
    console.log('=== 文件信息 ===');
    const fileFields = documentForm.getFieldsValue();
    Object.entries(fileFields).forEach(([key, value]) => {
      console.log(`${key}:`, value || '未上传');
    });
    console.groupEnd();

    // 5. 提交数据
    console.log('[handleComplete] Mode:', mode);
    
    // 确保提交的数据格式正确
    const finalSubmitData = {
      ...submitData,
      // 确保数字字段是数字类型
      baseSalary: Number(submitData.baseSalary),
      hourlyRate: Number(submitData.hourlyRate),
      renewalCount: Number(submitData.renewalCount),
      // 确保状态是数字
      status: Number(submitData.status) || 1
    };
    
    console.log('[handleComplete] Final submit data:', finalSubmitData);
    
    // 根据模式调用不同的API
    let response;
    if (mode === 'edit' && employeeId) {
      // 编辑模式：调用更新API
      console.log('[handleComplete] Calling employeeApi.updateEmployee');
      finalSubmitData.id = employeeId; // 添加员工ID
      response = await employeeApi.updateEmployee(finalSubmitData);
      console.log('[handleComplete] Update response:', response);
    } else {
      // 创建模式：调用创建API
      console.log('[handleComplete] Calling employeeApi.createEmployee');
      response = await employeeApi.createEmployee(finalSubmitData);
      console.log('[handleComplete] Create response:', response);
    }

    // 6. 处理响应
    if (response && response.code === 200) {
      const resultEmployeeId = mode === 'edit' ? employeeId : response.data;
      console.log('[handleComplete] Success, employee ID:', resultEmployeeId);

      // 7. 清理并显示成功
      localStorage.removeItem('employeeFormDraft');
      
      // 只在创建模式下显示成功消息
      if (mode === 'create') {
        message.success(`员工 ${submitData.name} 创建成功`);
      }
      
      onBack({
        type: 'employee-form-complete',
        employeeId: resultEmployeeId,
        employeeName: submitData.name,
        close: true
      });
    } else {
      throw new Error(response?.message || (mode === 'edit' ? '更新员工失败' : '创建员工失败'));
    }

  } catch (error) {
    console.error('[handleComplete] Error:', error);
    
    // 更详细的错误处理
    if (error.response) {
      console.error('[handleComplete] Server error response:', {
        status: error.response.status,
        data: error.response.data,
        headers: error.response.headers
      });
      
      const errorMessage = error.response.data?.message || 
                         error.response.statusText || 
                         '服务器返回错误';
      message.error(`创建失败: ${errorMessage}`);
    } else if (error.request) {
      console.error('[handleComplete] Request was made but no response received:', error.request);
      message.error('请求发送成功，但没有收到服务器响应');
    } else {
      console.error('[handleComplete] Error setting up the request:', error.message);
      message.error(`请求配置错误: ${error.message}`);
    }
  } finally {
    setSaving(false);
    console.groupEnd();
  }
};

  const handlePreview = () => {
    if (!employeeData[`step${currentStep}`]) {
      message.warning('请先保存当前步骤后再预览');
      return;
    }
    setPreviewVisible(true);
  };

  const renderPreviewModal = () => {
    const previewData = {
      step0: employeeData.step0 || {},
      step1: currentStep >= 1 ? employeeData.step1 || {} : null
    };

    const formatDate = (date) => {
      const d = safeDayjs(date);
      return d ? d.format('YYYY-MM-DD') : '-';
    };

    return (
      <Modal
        title="员工信息预览"
        visible={previewVisible}
        width={800}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <Descriptions column={1} bordered>
          <Descriptions.Item label="项目编号">{previewData.step0.projectCode}</Descriptions.Item>
          <Descriptions.Item label="所属单位">{previewData.step0.clientUnit}</Descriptions.Item>
          <Descriptions.Item label="所在部门">{previewData.step0.department}</Descriptions.Item>
          <Descriptions.Item label="所在团队">{previewData.step0.team}</Descriptions.Item>
          <Descriptions.Item label="岗位名称">{previewData.step0.position}</Descriptions.Item>
          <Descriptions.Item label="员工类型">
            {mockEmployeeTypes.find(t => t.value === previewData.step0.employeeType)?.label || previewData.step0.employeeType}
          </Descriptions.Item>
          <Descriptions.Item label="姓名">{previewData.step0.name}</Descriptions.Item>
          <Descriptions.Item label="性别">{previewData.step0.gender === 'male' ? '男' : '女'}</Descriptions.Item>
          <Descriptions.Item label="婚姻状况">
            {previewData.step0.maritalStatus === 'M' ? '已婚' : 
            previewData.step0.maritalStatus === 'S' ? '未婚' : '离异'}
          </Descriptions.Item>
          <Descriptions.Item label="籍贯">{previewData.step0.nativePlace}</Descriptions.Item>
          <Descriptions.Item label="民族">
            {mockEthnicGroups.find(e => e.value === previewData.step0.ethnicity)?.label || previewData.step0.ethnicity}
          </Descriptions.Item>
          <Descriptions.Item label="政治面貌">
            {mockPoliticalStatus.find(p => p.value === previewData.step0.politicalStatus)?.label || previewData.step0.politicalStatus}
          </Descriptions.Item>
          <Descriptions.Item label="身份证号">{previewData.step0.idCard}</Descriptions.Item>
          <Descriptions.Item label="生日">{formatDate(previewData.step0.birthday)}</Descriptions.Item>
          <Descriptions.Item label="户籍地址">{previewData.step0.registeredAddress}</Descriptions.Item>
          <Descriptions.Item label="现居住地址">{previewData.step0.currentAddress}</Descriptions.Item>
          <Descriptions.Item label="电话/微信">{previewData.step0.phone}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{previewData.step0.email}</Descriptions.Item>
          <Descriptions.Item label="入职时间">{formatDate(previewData.step0.hireDate)}</Descriptions.Item>
          <Descriptions.Item label="转正时间">{formatDate(previewData.step0.confirmationDate)}</Descriptions.Item>
          <Descriptions.Item label="学历/学位">
            {mockEducationLevels.find(e => e.value === previewData.step0.education)?.label || previewData.step0.education}
          </Descriptions.Item>
          <Descriptions.Item label="所学专业">{previewData.step0.major}</Descriptions.Item>
          <Descriptions.Item label="毕业院校">{previewData.step0.university}</Descriptions.Item>
          <Descriptions.Item label="毕业时间">{formatDate(previewData.step0.graduationDate)}</Descriptions.Item>
          <Descriptions.Item label="技能证书">{previewData.step0.skillCertificates}</Descriptions.Item>
          <Descriptions.Item label="基本工资">{previewData.step0.baseSalary}</Descriptions.Item>
          <Descriptions.Item label="紧急联系人">{previewData.step0.emergencyContact}</Descriptions.Item>
          <Descriptions.Item label="紧急联系电话">{previewData.step0.emergencyPhone}</Descriptions.Item>
          <Descriptions.Item label="银行卡号">{previewData.step0.bankAccount}</Descriptions.Item>
          <Descriptions.Item label="开户行">
            {mockBanks.find(b => b.value === previewData.step0.bankName)?.label || previewData.step0.bankName}
          </Descriptions.Item>
          <Descriptions.Item label="是否已续签合同">
            {previewData.step0.contractRenewed === 'Y' ? '是' : '否'}
          </Descriptions.Item>
          <Descriptions.Item label="续签合同次数">{previewData.step0.renewalCount}</Descriptions.Item>
          <Descriptions.Item label="劳动合同开始时间">{formatDate(previewData.step0.latestContractStart)}</Descriptions.Item>
          <Descriptions.Item label="劳动合同结束时间">{formatDate(previewData.step0.latestContractEnd)}</Descriptions.Item>
          <Descriptions.Item label="签合同公司">{previewData.step0.contractCompany}</Descriptions.Item>
          <Descriptions.Item label="备注">{previewData.step0.remarks}</Descriptions.Item>
          <Descriptions.Item label="状态">
            {previewData.step0.status === 'active' ? (
              <Tag color="green">在职</Tag>
            ) : previewData.step0.status === 'leave' ? (
              <Tag color="red">离职</Tag>
            ) : (
              <Tag color="orange">休假</Tag>
            )}
          </Descriptions.Item>
          <Descriptions.Item label="试用状态">
            {previewData.step0.probation === 'probation' ? (
              <Tag color="orange">试用期</Tag>
            ) : (
              <Tag color="green">已转正</Tag>
            )}
          </Descriptions.Item>

          {previewData.step1 && (
            <>
              <Descriptions.Item label="入职登记表">
                {previewData.step1.entryForm ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.entryForm)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="身份证复印件">
                {previewData.step1.idCardCopy ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.idCardCopy)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="学历毕业证书">
                {previewData.step1.diploma ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.diploma)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="学位证书">
                {previewData.step1.degreeCertificate ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.degreeCertificate)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="银行卡复印件">
                {previewData.step1.bankCardCopy ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.bankCardCopy)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="简历">
                {previewData.step1.resume ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.resume)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="离职证明">
                {previewData.step1.leavingCertificate ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.leavingCertificate)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="三甲体检报告">
                {previewData.step1.medicalReport ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.medicalReport)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="保密协议">
                {previewData.step1.confidentialityAgreement ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.confidentialityAgreement)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="员工培训协议">
                {previewData.step1.trainingAgreement ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.trainingAgreement)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="规章制度确认书">
                {previewData.step1.rulesConfirmation ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.rulesConfirmation)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
              <Descriptions.Item label="员工行为准则">
                {previewData.step1.codeOfConduct ? (
                  <a href={fileApi.getPreviewUrl(previewData.step1.codeOfConduct)} target="_blank" rel="noopener noreferrer">
                    查看文件
                  </a>
                ) : '未上传'}
              </Descriptions.Item>
            </>
          )}
        </Descriptions>
      </Modal>
    );
  };

  const renderBasicInfoStep = () => (
    <Card title="员工基本信息" style={{ marginTop: 16 }}>
      <Form
        form={form}
        layout="vertical"
      >
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="projectCode"
              label="项目编号"
            >
              <Input placeholder="请输入项目编号" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="clientUnit"
              label="所属单位"
            >
              <Input placeholder="请输入所属单位" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="department"
              label="所在部门"
            >
              <Select
                showSearch
                placeholder="请选择部门"
                filterOption={false}
                onSearch={setDepartmentSearch}
              >
                {mockDepartments
                  .filter(dept => dept.name.includes(departmentSearch))
                  .map(dept => (
                    <Option key={dept.id} value={dept.name}>
                      {dept.name}
                    </Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="team"
              label="所在团队"
            >
              <Select
                showSearch
                placeholder="请选择团队"
                filterOption={false}
                onSearch={setTeamSearch}
              >
                {mockTeams
                  .filter(team => team.name.includes(teamSearch))
                  .map(team => (
                    <Option key={team.id} value={team.name}>
                      {team.name}
                    </Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="position"
              label="岗位名称"
            >
              <Select
                showSearch
                placeholder="请选择岗位"
                filterOption={false}
                onSearch={setPositionSearch}
              >
                {mockPositions
                  .filter(pos => pos.name.includes(positionSearch))
                  .map(pos => (
                    <Option key={pos.id} value={pos.name}>
                      {pos.name}
                    </Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="employeeType"
              label="员工类型"
              rules={[{ required: true, message: '请选择员工类型' }]}
            >
              <Select placeholder="请选择员工类型">
                {mockEmployeeTypes.map(type => (
                  <Option key={type.value} value={type.value}>
                    {type.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="name"
              label="姓名"
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="gender"
              label="性别"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              <Select placeholder="请选择性别">
                <Option value="M">男</Option>
                <Option value="F">女</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="maritalStatus"
              label="婚姻状况"
              rules={[{ required: true, message: '请选择婚姻状况' }]}
            >
              <Select placeholder="请选择婚姻状况">
                {mockMaritalStatus.map(status => (
                  <Option key={status.value} value={status.value}>
                    {status.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="nativePlace"
              label="籍贯"
              rules={[{ required: true, message: '请输入籍贯' }]}
            >
              <Input placeholder="请输入籍贯" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="ethnicity"
              label="民族"
              rules={[{ required: true, message: '请选择民族' }]}
            >
              <Select placeholder="请选择民族">
                {mockEthnicGroups.map(ethnic => (
                  <Option key={ethnic.value} value={ethnic.value}>
                    {ethnic.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="politicalStatus"
              label="政治面貌"
              rules={[{ required: true, message: '请选择政治面貌' }]}
            >
              <Select placeholder="请选择政治面貌">
                {mockPoliticalStatus.map(status => (
                  <Option key={status.value} value={status.value}>
                    {status.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="idCard"
              label="身份证号"
              rules={[
                { required: true, message: '请输入身份证号' },
                { pattern: /^\d{17}[\dXx]$/, message: '请输入有效的身份证号' }
              ]}
            >
              <Input placeholder="请输入身份证号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="birthday"
              label="生日"
              rules={[{ required: true, message: '请选择生日' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="registeredAddress"
          label="户籍地址"
          rules={[{ required: true, message: '请输入户籍地址' }]}
        >
          <Input placeholder="请输入户籍地址" />
        </Form.Item>

        <Form.Item
          name="currentAddress"
          label="现居住地址"
          rules={[{ required: true, message: '请输入现居住地址' }]}
        >
          <Input placeholder="请输入现居住地址" />
        </Form.Item>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="phone"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="wechat"
              label="微信号"
            >
              <Input placeholder="请输入微信号" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="hireDate"
              label="入职时间"
              rules={[{ required: true, message: '请选择入职时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="confirmationDate"
              label="转正时间"
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="education"
              label="学历/学位"
              rules={[{ required: true, message: '请选择学历/学位' }]}
            >
              <Select placeholder="请选择学历/学位">
                {mockEducationLevels.map(edu => (
                  <Option key={edu.value} value={edu.value}>
                    {edu.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="major"
              label="所学专业"
              rules={[{ required: true, message: '请输入所学专业' }]}
            >
              <Input placeholder="请输入所学专业" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="university"
              label="毕业院校"
              rules={[{ required: true, message: '请输入毕业院校' }]}
            >
              <Input placeholder="请输入毕业院校" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="graduationDate"
              label="毕业时间"
              rules={[{ required: true, message: '请选择毕业时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="skillCertificates"
              label="技能证书"
            >
              <Input placeholder="请输入技能证书，多个用逗号分隔" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="baseSalary"
              label="基本工资"
              rules={[{ required: true, message: '请输入基本工资' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                precision={2}
                placeholder="请输入基本工资"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="emergencyContact"
              label="紧急联系人"
              rules={[{ required: true, message: '请输入紧急联系人' }]}
            >
              <Input placeholder="请输入紧急联系人" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="emergencyPhone"
              label="紧急联系电话"
              rules={[
                { required: true, message: '请输入紧急联系电话' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
              ]}
            >
              <Input placeholder="请输入紧急联系电话" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="bankAccount"
              label="银行卡号"
              rules={[{ required: true, message: '请输入银行卡号' }]}
            >
              <Input placeholder="请输入银行卡号" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="bankName"
              label="开户行"
              rules={[{ required: true, message: '请选择开户行' }]}
            >
              <Select placeholder="请选择开户行">
                {mockBanks.map(bank => (
                  <Option key={bank.value} value={bank.value}>
                    {bank.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="contractRenewed"
              label="是否已续签合同"
            >
              <Select placeholder="请选择">
                {mockContractRenewed.map(item => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="renewalCount"
              label="续签合同次数"
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                placeholder="请输入续签合同次数"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="contractCompany"
              label="签合同公司"
              rules={[{ required: true, message: '请输入签合同公司' }]}
            >
              <Input placeholder="请输入签合同公司" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="latestContractStart"
              label="劳动合同开始时间"
              rules={[{ required: true, message: '请选择劳动合同开始时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="latestContractEnd"
              label="劳动合同结束时间"
              rules={[{ required: true, message: '请选择劳动合同结束时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            {mockStatusOptions.map(status => (
              <Option key={status.value} value={status.value}>
                {status.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="probation"
          label="试用状态"
          rules={[{ required: true, message: '请选择试用状态' }]}
        >
          <Select placeholder="请选择试用状态">
            <Option value="probation">试用期</Option>
            <Option value="confirmed">已转正</Option>
          </Select>
        </Form.Item>

        <Form.Item name="remarks" label="备注">
          <TextArea rows={3} placeholder="请输入备注信息" />
        </Form.Item>
      </Form>
    </Card>
  );

const renderDocumentStep = () => (
  <Card title="员工文件附件" style={{ marginTop: 16 }}>
    <Form form={documentForm} layout="vertical">
      {documentTypes.map(doc => {
        const filePath = documentForm.getFieldValue(doc.name);
        const selectedFile = selectedFiles[doc.name];
        
        // 构建文件列表
        let fileList = [];
        if (filePath) {
          // 已上传的文件
          fileList = [{
            uid: '-1',
            name: filePath.split('/').pop(),
            status: 'done',
            url: fileApi.getPreviewUrl(filePath)
          }];
        } else if (selectedFile) {
          // 选中的文件（未上传）
          fileList = [{
            uid: '-2',
            name: selectedFile.name,
            status: 'uploading',
            percent: 0
          }];
        }
        
        return (
          <Form.Item key={doc.name} name={doc.name} label={doc.label}>
            <Upload
              fileList={fileList}
              customRequest={({ file, onSuccess }) => {
                // 选择文件但不立即上传
                selectFile(doc.name, file);
                onSuccess(); // 立即标记为成功，实际上传在完成时进行
              }}
              listType="text"
              maxCount={1}
              showUploadList={{
                showRemoveIcon: true,
                showDownloadIcon: false,
                showPreviewIcon: false
              }}
              onRemove={() => {
                // 移除选中的文件
                setSelectedFiles(prev => {
                  const newFiles = { ...prev };
                  delete newFiles[doc.name];
                  return newFiles;
                });
                // 清除表单字段
                documentForm.setFieldsValue({ [doc.name]: undefined });
              }}
            >
              <Button icon={<PlusOutlined />} loading={uploadingFiles[doc.name]}>
                {selectedFile ? '重新选择' : '选择文件'}
              </Button>
            </Upload>
            {selectedFile && (
              <div style={{ marginTop: 8, color: '#1890ff', fontSize: '12px' }}>
                已选择: {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)}MB)
                <br />
                <span style={{ color: '#666' }}>点击"完成"按钮后将自动上传</span>
              </div>
            )}
          </Form.Item>
        );
      })}
    </Form>
  </Card>
);

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return renderBasicInfoStep();
      case 1:
        return renderDocumentStep();
      default:
        return renderBasicInfoStep();
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Steps current={currentStep} style={{ marginBottom: 32 }}>
        {steps.map((step, index) => (
          <Step key={index} title={step.title} icon={step.icon} />
        ))}
      </Steps>

      {renderStepContent()}

      <div style={{ 
        marginTop: 24, 
        textAlign: 'center',
        padding: '16px 0',
        borderTop: '1px solid #f0f0f0'
      }}>
        <Space size="large">
          {currentStep > 0 && (
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={() => setCurrentStep(currentStep - 1)}
              size="large"
            >
              上一步
            </Button>
          )}
          
          {currentStep === 1 && (
            <Button 
              icon={<EyeOutlined />}
              onClick={handlePreview}
              disabled={!employeeData[`step${currentStep}`]}
              size="large"
            >
              预览
            </Button>
          )}
          
          <Button 
            type="primary" 
            icon={<ArrowRightOutlined />} 
            onClick={currentStep === steps.length - 1 ? handleComplete : handleNext}
            size="large"
          >
            {currentStep === steps.length - 1 ? '完成' : '下一步'}
          </Button>
        </Space>
      </div>

      {renderPreviewModal()}
    </div>
  );
};

export default EmployeeForm;